import React, { createContext, useContext } from 'react';

// 创建一个上下文对象
const LevelContext = createContext<number>(0);

function Heading({children}: any) {
    // 组件会使用 UI 树中在它上层最近的那个 <LevelContext.Provider> 传递过来的值。
    const level = useContext<number>(LevelContext);
    switch (level) {
        case 1:
            return <h1>{ children }</h1>;
        case 2:
            return <h2>{ children }</h2>;
        case 3:
            return <h3>{ children }</h3>;
        case 4:
            return <h4>{ children }</h4>;
        case 5:
            return <h5>{ children }</h5>;
        case 6:
            return <h6>{ children }</h6>;
        default:
            throw Error('未知的 level：' + level);
    }
}

function Section({children}: any) {
    const level = useContext<number>(LevelContext);
    return (
        <section className="section">
            {/* 提供 context */ }
            <LevelContext.Provider value={ level + 1 }>
                { children }
            </LevelContext.Provider>
        </section>
    );
}

const ContextHook = () => {
    return (
        <Section>
            <Heading>主标题11</Heading>
            <Section>
                <Heading>副标题22</Heading>
                <Heading>副标题22</Heading>
                <Heading>副标题22</Heading>
                <Section>
                    <Heading>子标题33</Heading>
                    <Heading>子标题33</Heading>
                    <Heading>子标题33</Heading>
                    <Section>
                        <Heading>子子标题44</Heading>
                        <Heading>子子标题44</Heading>
                        <Heading>子子标题44</Heading>
                        <Section>
                            <Heading>子子标题55</Heading>
                            <Heading>子子标题55</Heading>
                            <Heading>子子标题55</Heading>
                        </Section>
                    </Section>
                </Section>
            </Section>
        </Section>
    );
};

export default ContextHook;